var jMenuTree;
var belongtoType;//用于区分是前台还是后台
$j(document).ready(function () {
	
});



//点击树节点action
function clickTreeItemAction(belongto,curId){
	if(belongto)
		belongtoType=belongto;
	activeTreeItem(curId);
}

//根据树节点显示按钮
function displayButtons(menuId){
	disableIconBtn("moveUp");
	disableIconBtn("moveDown");
	disableIconBtn("add");
	disableIconBtn("delete");
	disableIconBtn("save");
	if(menuId == null){
		//如果没有什么节点
		disableIconBtn("moveUp");
		disableIconBtn("moveDown");
		disableIconBtn("add");
		disableIconBtn("delete");
		disableIconBtn("save");
	}else if(menuId == ""){
		//如果是新增节点则只开发保存按钮
		disableIconBtn("moveUp");
		disableIconBtn("moveDown");
		disableIconBtn("add");
		disableIconBtn("delete");
		enableIconBtn("save");
	}else if(menuId<1){
		//如果是根节点则屏蔽删除按钮
		disableIconBtn("moveUp");
		disableIconBtn("moveDown");
		enableIconBtn ("add");
		disableIconBtn("delete");
		disableIconBtn ("save");
	}else{
		//开放全部
		enableIconBtn ("moveUp");
		enableIconBtn ("moveDown");
		enableIconBtn ("add");
		enableIconBtn ("delete");
		enableIconBtn ("save");
	}

}
//加载目录编辑form
function editMenuForm(menuId,callback){
	displayButtons(menuId);//先将所有按钮disable	
	showMenuForm(__ctxPath+"/system/"+belongtoType+"/dialog.html?doAction=edit&menuId="+menuId);
	//showMenuForm(__ctxPath+"/product/appMenu/blank.html?doAction=edit&menuId="+menuId,loadHtmlEditor);
}
//新增目录
function createMenu(){
	displayButtons("");//先将所有按钮disable
	var treeItem=getMenuItemJSON(jMenuTree.getSelected());
	if(treeItem){
		if(parseInt(treeItem.depth) < 3){
			$j("#menuResults").empty();			
			showMenuForm(__ctxPath+"/system/"+belongtoType+"/dialog.html?doAction=edit&parentId="+treeItem.id);
		}else{
			jAlert(__FMT.appMenuList_overMaxDepth);
		}
	}
}

//在本页以ajaxPage方式打开menuForm 
function showMenuForm(url){
	$j("#menuResults").loading().load(url,null);
}

//将目录置前
function upMenu(){
	var jNode = jMenuTree.getSelected();
	if(jNode.length > 0 && jNode.prevAll("[id]").size()!=0){
		moveActiveMenuUp();
		updateMenusSortOrder(jNode);
	}else{
		//已经是第一个元素，不需要再置前
	}
	
}
//将目录放后
function downMenu(){
	var jNode = jMenuTree.getSelected();
	if(jNode.length > 0  && jNode.nextAll("[id]").size()!=0){
		moveActiveMenuDown();
		updateMenusSortOrder(jNode);
	}else{
		//已经是最后一个元素，不需要再放后
	}
}

//更新目录排序
function updateMenusSortOrder(jNode){
	var categoires=jNode.parent("ul").children("li[id]");
	var paramData="";
	for(var i=0;i<categoires.length;i++){
		var id=categoires.get(i).id;
		paramData+="menuIds="+id+"&";
	}
	$j.post(__ctxPath+"/system/"+belongtoType+"/dialog.html?doAction=updateMenusSortOrder",paramData);
}

//删除目录
function delMenu(){
	var treeItem=getMenuItemJSON(jMenuTree.getSelected());
	if(treeItem&&confirm(__FMT.common_message_confirmDeleteThis+treeItem.name+"?")){
		var paramData={menuId:treeItem.id};
		$j.post(__ctxPath+"/system/"+belongtoType+"/dialog.html?doAction=delete",paramData,delMenuCallback,"json");
	}
}
//删除目录callback
function delMenuCallback(data){
	sysMsg(data.message,(data.result!=1));
	if(data.result==1){
		//fill div
		deleteTreeItem(jMenuTree);
		displayButtons();
		//start:显示父目录
		activeTreeItem(data.parentId);
		editMenuForm(""+data.parentId);
		//end:显示父目录
	}
}
//分页
function fnOnGoToPage(){
	searchMenus(false);
}

//搜索文章 isNew标示是否新的搜索,param标示是否自定义参数搜索
function searchMenus(isNew,menuId){
	var postData;
	var url=__ctxPath+"/system/"+belongtoType+"/dialog.html?doAction=search";
	if(isNew){
		url+="&btnSearch=1";
		if(!menuId){
			postData = $j('#menuSearchCriteria :input').serializeArray();
			$j("#menuResults").load(url,postData);
		}else{
			$j("#menuResults").load(url,{"parentId":menuId});
		}
	}else{
		postData = $j('#menuResults :input').serializeArray();
		$j("#menuResults").load(url,postData);
	} 
	displayButtons(menuId);
}
//验证
function validateAction(){
	//validate the form	  	  
    if(!validateAppMenu($j("#appMenuForm").get(0)) ){
    	focusOnInvalidTab();
    	return false;
   	}
    return true;
}
//保存目录
function saveMenu(){
	var treeItem=getMenuItemJSON(jMenuTree.getSelected());
	if((!treeItem)||!validateAction()){
    	return ;
    }
    var entityName=$j("input#title").val();
   	if(confirm( __FMT.common_message_confirmSaveThis+"("+entityName+")?")){
    	var postData="";
    	postData += $j('#appMenuForm :input').serialize();
    	var url=$j('#appMenuForm').attr('action')+"?doAction=save";
    	$j.post(url,postData,saveMenuCallback,"json");
   	}
   	return false;
}

//保存目录callback
function saveMenuCallback(data){
	if(data.error && data.error!=""){
		jAlert(data.error);
		return ;
	}
   
 	//保存成功
 	if($j("#menuId").val()==""){
 		//case:新增目录
 		$j("#menuId").val(data.menuId);
 		addMenuItemToTree(data.menuId,data.title+"(0)",data.title,data.depth,data.type);
 	}else{
 		//case:编辑目录
 		var jNode = jMenuTree.getSelected();
 		jNode.find('span:first').html(data.title+"("+data.count+")");
 	}
	setTimeout("sysMsg('"+__FMT.appMenuDetail_save_successed+data.title+".')",0);
	
	displayButtons(""+data.menuId);
	if(data.threeLevel){
		disableIconBtn ("add");
	}else{
		enableIconBtn ("add");
	}
   
}


//将传入的jNode [li(jquery object)]构造为JSON对象{id,name,depth,categoryType}
function getMenuItemJSON(jNode){
	if(jNode.length >0){
		var id=jNode[0].id;
		var name=$j('span ',jNode).attr("name");
		var depth = $j('span ',jNode).attr("depth");
		var type=$j('span ',jNode).attr("type");
		treeItem={'id':id,'name':name,'depth':depth,'type':type};
		return treeItem;
	}else{
		return null;
	}
}
//将tree的激活节点向上移动
function moveActiveMenuUp(){
	var jNode=jMenuTree.getSelected();
	var line=jNode.prev();
	line.insertBefore(line.prev().prev());
	jNode.insertAfter(line);
	var parent=jNode.parent("ul").parent("li[id]");
	refreshChildrenClass(parent);
}
//将tree的激活节点向下移动
function moveActiveMenuDown(){
	var jNode=jMenuTree.getSelected();
	var line=jNode.prev();
	jNode.insertAfter(jNode.next().next());
	line.insertBefore(jNode);
	var parent=jNode.parent("ul").parent("li[id]");
	refreshChildrenClass(parent);
}

//更新父元素的所有子元素li的class,最后一个子元素的class应为line-last
//输入：父元素li的jquery对象
function refreshChildrenClass(jNode){
	var children=jNode.children("ul").children("li");
	var lastChildren=children.slice(children.length-2);
	$j.each(children,function(){
		$j(this).attr("class",$j(this).attr("class").replace("-last",""));
	});
	$j.each(lastChildren,function(){
		$j(this).attr("class",$j(this).attr("class")+"-last");
	});
}
//在当前激活元素node[li]下增加一个node[li]
function addMenuItemToTree(itemId,title,name,depth,type,icon){
	var selectedNode=jMenuTree.getSelected();
	if(selectedNode.children("ul").length==0){
		jMenuTree.convertToFolder(selectedNode);
	}
	if(selectedNode.children('ul.ajax').length!=0){
		//使用ajaxload子文件且当前文件夹未打开则
		return;  //do nothing
	}
	jMenuTree.addNode(itemId,title);
	$j("#"+itemId,$j(jMenuTree)).children("span:first").attr("name",name);
	$j("#"+itemId,$j(jMenuTree)).children("span:first").attr("depth",depth);
	$j("#"+itemId,$j(jMenuTree)).children("span:first").attr("type",type);
	if(icon)
		$j("#"+itemId,$j(jMenuTree)).children("span:first").prepend(icon);
}
//删除当前激活元素
function deleteTreeItem(){
	var selectedNode=jMenuTree.getSelected();
	var parentNode=selectedNode.parents('li:first');
	var otherNodes=selectedNode.siblings("li[id]");
	if(otherNodes.length==0){
		jMenuTree.convertToDoc(parentNode);
	}else{
		jMenuTree.delNode();
	}
}
//设置激活元素 menuId为li中的id
function activeTreeItem(menuId){
	$j(".active",$j(jMenuTree)).attr("class","text");
	//var treeItem=getMenuItemJSON(jMenuTree.getSelected());
	$j("#"+menuId+" >span",$j(jMenuTree)).attr("class","active");
	if(menuId>0){
		editMenuForm(menuId);
	}else{
		searchMenus(true,menuId)
	}
}